using SqlSugar;

namespace TestWebApi.Util;

public class DatabaseContext
{
     private readonly Dictionary<string, ISqlSugarClient> _dbContexts;
    private bool _disposed;

    public DatabaseContext(IConfiguration configuration)
    {
        _dbContexts = new Dictionary<string, ISqlSugarClient>();
        // 初始化App settings的数据库连接字符串
        foreach (var section in configuration.GetSection("ConnectionStrings").GetChildren())
        {
            var connectionString = section.Value;
            var dbContext = new SqlSugarClient(new ConnectionConfig
            {
                InitKeyType = InitKeyType.Attribute, // 主键类型(自增主键)
                ConnectionString = connectionString, // 连接字符串
                DbType = DbType.MySql, // 数据库类型
                IsAutoCloseConnection = true, //是否自动关闭连接
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    EntityService = (property, column) =>
                    {
                        if (property.PropertyType.IsEnum) //判断实体类里的属性是否为枚举类型
                        {
                            column.DataType = "int"; // 将枚举类型映射为整数类型(role)
                        }
                    }
                }
            });
            _dbContexts.Add(section.Key, dbContext); // 添加到字典中
            //打印_dbContex
            // foreach (var variable in _dbContexts)
            // {
            //     AppLogger.Information($"数据库连接字典{variable.Key}已初始化");
            // }
            //
        }
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }


    /// <summary>
    /// 获取指定连接字符串的 SqlSugarClient 实例
    /// </summary>
    /// <param name="connectionName">连接字符串名称</param>
    /// <returns>SqlSugarClient 实例</returns>
    public ISqlSugarClient GetDbContext(string connectionName)
    {
        if (_dbContexts.TryGetValue(connectionName, out var dbContext)) AppLogger.Information($"获取数据库连接{connectionName}成功");  return dbContext;
      //  AppLogger.Error(new Exception("连接字符串未配置"), $"连接字符串 {connectionName} 未配置");
        throw new InvalidOperationException($"连接字符串 {connectionName} 未配置");
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    /// <param name="disposing">是否释放托管资源</param>
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
                // 释放托管资源
                foreach (var dbContext in _dbContexts.Values)
                    dbContext.Dispose();

            // 释放非托管资源
            // 在这里释放任何需要手动释放的非托管资源

            _disposed = true;
        }
    }

    /// <summary>
    /// 析构函数
    /// </summary>
    ~DatabaseContext()
    {
        Dispose(false);
    }
}